package com.yd;

import com.yd.bean.DocNodeBean;
import com.yd.bean.NodeBean;
import com.yd.bean.TranslateBean;
import com.yd.bean.TranslateMapBean;
import com.yd.config.Config;
import com.yd.util.FileUtils;
import com.yd.util.StringUtil;
import com.yd.util.XmlUtil;
import org.jdom2.Element;
import org.jdom2.Text;

import java.io.*;
import java.util.*;

/**
 * 根据原始的xml文件和翻译好的原始文本->翻译的文本对应，合并到新的翻译文本中
 * 将原始的xml和翻译对照文本放在resource/translate目录下，对照文本对应根据TAb分隔符分割
 */
public class MergeTranslateByDomClient {

    public static void main(String[] args) {
        File mergeInputFile = Config.translate;
        mergeInfo(mergeInputFile);
    }

    /**
     * 合并翻译过后的文本为Android 字符串文件格式
     *
     * @param inputFile
     */
    public static void mergeInfo(File inputFile) {
        System.out.println("mergeInfo>>>dir >>>>path = " + inputFile.getPath());
        List<File> orderFiles = new ArrayList<>();
        if (inputFile.exists() && inputFile.isDirectory()) {
            for (File file : inputFile.listFiles()) {
//                String name = FileUtils.getFileNameNoExtension(file);
//                String fileExtension = Config.translateExt;
                File needOrderFile = new File(file.getParentFile(), Config.translateFileName);
                if (!file.getName().contains(Config.translateFileName) &&
                        !file.getName().contains(Config.translateSuffix)) {
                    if (needOrderFile.exists()) {
                        //选项需要排序的文件
                        orderFiles.add(file);
                    } else {
                        System.out.println("mergeInfo>>>翻译后的文本文件不存在 >>>>path = " + needOrderFile.getPath());
                    }
                }
            }
        } else {
            System.out.println("mergeInfo>>>遍历文件 >>>>inputFile = " + inputFile.getPath() + "====不存在，编译一下项目Build->Build Project");
        }

        if (orderFiles == null || orderFiles.size() == 0) {
            System.out.println("mergeInfo>>>>>path = " + inputFile.getPath() + ">>>>为空目录");
        } else {
//            Map<String, String> extMap = obtainFileName(orderFiles);
            //翻译后的文件
            File inputTranslateFile = new File(inputFile, Config.translateFileName);
            if (!inputFile.exists() || !inputTranslateFile.exists()) {
                System.out.print(inputFile.getPath() + "\n或者\n" + inputTranslateFile + "\n不存在！！");
            } else {
                TranslateMapBean translateBeans = readTranslateBean(inputTranslateFile);
                for (File file : orderFiles) {
                    mergeTranslatedText(file, translateBeans);
                }
            }
        }
    }

    /**
     * 获取本目录下需要解析的文件名
     *
     * @param files
     * @return
     */
    public static Map<String, String> obtainFileName(List<File> files) {
        Map<String, String> names = new HashMap<>();
        for (File file : files) {
            if (file.isFile()) {
                String name = FileUtils.getFileNameNoExtension(file);
                String extension = FileUtils.getFileExtension(file);
                if (!names.containsKey(name)) {
                    System.out.println("合并的文件名>>>>>name = " + name);
                    names.put(name, extension);
                }
            } else if (file.isDirectory()) {
//                File newOut = new File(outFile, file.getName());
                mergeInfo(file);
            }
        }
        return names;
    }

    public static TranslateMapBean readTranslateBean(File inputTranslateFile) {
        TranslateMapBean translateBeans = new TranslateMapBean();
        try (BufferedReader readerTrans = new BufferedReader(new FileReader(inputTranslateFile))) {
            String lineText;
            while ((lineText = readerTrans.readLine()) != null) {
                if (lineText != null) {
                    lineText.trim();
                    String[] lineStrs = lineText.split(Config.TranslateKeyValueDivider);
                    if (lineStrs.length >= 2) {
                        TranslateBean translateBean = new TranslateBean();
                        translateBean.sourceText = StringUtil.replaceSpecialChar(lineStrs[0].trim());
                        translateBean.translateText = StringUtil.replaceSpecialChar(lineStrs[1].trim());
                        translateBeans.translateBeans.add(translateBean);
                        translateBeans.translateMap.put(translateBean.sourceText, translateBean);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return translateBeans;
    }

    /**
     * @param inputFile 翻译前的文件
     */
    public static void mergeTranslatedText(File inputFile, TranslateMapBean translateBeans) {
        System.out.println("========================================");
        File parentFile = inputFile.getParentFile();
        System.out.println("合并文件目录>>>>" + parentFile.getPath());
        if (parentFile.isDirectory() && !parentFile.exists()) {
            System.out.println("创建合并文件目录>>>>" + parentFile.getPath());
            parentFile.mkdirs();
        }
        File mergeFile = new File(inputFile.getParentFile(), FileUtils.getFileNameNoExtension(inputFile)
                + Config.translateSuffix + "." + FileUtils.getFileExtension(inputFile));

        FileUtils.createFileByDeleteOldFile(mergeFile);
        System.out.println("开始合并文件>>>>" + mergeFile.getPath());

        List<NodeBean> nokeys = new ArrayList<>();
        List<NodeBean> noNeedTranslate = new ArrayList<>();
        DocNodeBean docNodeBean = XmlUtil.parseSourceDoc(inputFile.getPath());
        List<NodeBean> newNodeList = new ArrayList<>();
        for (NodeBean nodeBean : docNodeBean.list) {
            if (nodeBean.translatable) {
                String fixText = nodeBean.text.trim();
                StringBuilder stringBuilder = null;
                if (fixText.contains("\n")) {
                    String[] textArray = fixText.split("\n");
                    stringBuilder = new StringBuilder();
                    for (String subText : textArray) {
                        stringBuilder.append(subText.trim());
                    }
                    fixText = stringBuilder.toString();
                }
                TranslateBean translateBean = translateBeans.translateMap.get(fixText);
                if (translateBean != null) {
                    nodeBean.text = translateBean.translateText;
                    newNodeList.add(nodeBean);
                } else {
                    if(nodeBean.text.contains("![CDATA[")){
                        newNodeList.add(nodeBean);
                    }
                    nokeys.add(nodeBean);
                    docNodeBean.nodeMap.remove(nodeBean.key);
                }
            } else {
                noNeedTranslate.add(nodeBean);
            }
        }
        if (!Config.isUserSourceText) {
            docNodeBean.list = newNodeList;
        }
        docNodeBean.list.removeAll(noNeedTranslate);
        //保持匹配的翻译的文案==================================================================================================
        System.out.println("mergeTranslatedText==合并成功键值对===filename=" + inputFile.getName() + "===数量:" + newNodeList.size());
        XmlUtil.writeMergeTranslate(docNodeBean, mergeFile);

        //输出不需要翻译的文案==================================================================================================
        System.out.println();
        System.out.println("mergeTranslatedText==不需要翻译键值对===filename=" + inputFile.getName() + "===数量:" + noNeedTranslate.size());
        for (NodeBean nodeBean : noNeedTranslate) {
            System.err.println("mergeTranslatedText===不需要翻译键值对===filename=" + inputFile.getName() + ">>key=" + nodeBean.key + "==value=" + nodeBean.text);
        }

        //输出翻译文件中不存在文案==================================================================================================
        System.out.println();
        if (nokeys.size() > 0) {
            System.err.println("mergeTranslatedText==合并失败键值对===filename=" + inputFile.getName() + "===数量:" + nokeys.size());
        }
        if (Config.isUserSourceText) {
            docNodeBean.list = newNodeList;
            if (nokeys.size() > 0) {
                System.err.println("mergeTranslatedText==复制不存在的键值对到翻译后的文件中===filename=" + inputFile.getName() + "===数量:" + nokeys.size());
            }
        }
        for (NodeBean nodeBean : nokeys) {
            System.err.println("mergeTranslatedText===翻译文件中不存在键值对===filename=" + inputFile.getName() + ">>key=" + nodeBean.key + "==value=" + nodeBean.text);
        }
    }
}
